package com.edushare.common.dao;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.Curricula;
import com.edushare.common.vo.ElectivePreference;
import com.edushare.common.vo.SemesterCourses;
import com.edushare.common.vo.Users;

public class ElectivePreferenceDAO extends CayenneBasedDAO {

	private static final Log log = LogFactory.getLog(ElectivePreferenceDAO.class);
	
	public ElectivePreferenceDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}

	public void addSetOfPreferences(Users user, SemesterCourses course,
			int groupId, int preference) {
		ElectivePreference ePref = new ElectivePreference();

		ePref.setElective(course);
		ePref.setElectiveGroup(groupId);
		ePref.setPreferenceNumber(preference);
		ePref.setSelected(ElectivePreference.PENDING_SELECTION);
		ePref.setUser(user);
		ePref.setTimestamp(new Date());
		
		getDataContext().registerNewObject(ePref);
		getDataContext().commitChanges();
	}

	public ElectivePreference getPreference(Users user, SemesterCourses course,
			int groupId) {
		List<ElectivePreference> ePref = user.getPreferences();
		for (ElectivePreference e : ePref) {
			if (e.getElectiveGroup() == groupId && e.getElective() == course) {
				return e;
			}
		}
		return null;
	}

	public boolean isCompleted(Users user, Curricula curr, int groupId, int sem) {
		List<ElectivePreference> ePref = user.getPreferences();
		
		List<SemesterCourses> semCourses = curr.getSemesterCourses();
		SemesterCourses sc = null;
		for (SemesterCourses s : semCourses) {
			if (s.getParentSemCourse() != null
					&& s.getElectiveGroup() == groupId
					&& s.getSemesterNo() == sem) {
				sc = s;
				break;
			}
		}

		if (sc == null)
			return false;

		for (ElectivePreference e : ePref) {
			if (e.getElectiveGroup() == groupId && e.getElective() == sc) {
				return true;
			}
		}

		return false;
	}

	public SemesterCourses getCourse(Users user, int preference, int groupId) {
		List<ElectivePreference> ePref = user.getPreferences();
		for (ElectivePreference e : ePref) {
			if (e.getElectiveGroup() == groupId
					&& e.getPreferenceNumber() == preference) {
				return e.getElective();
			}
		}
		return null;
	}

}
